<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\RechercheSejourTable;
use Zend\Session\Container; // We need this when using sessions
use Zend\Http\Header\SetCookie;

class ResultatsController extends AbstractActionController
{
	protected $RechercheSejourTable;

    public function resultatsAction()
    {
    	$this->layout('layout/layoutresultats');

		$sejoursFiltres = $this->NouvelleRecherche();

		$resultat_session = new Container('resultatsession');
		$resultat_session->data = $sejoursFiltres;
    }

    public function RechercheAction()
	{
		if($_SERVER['REQUEST_METHOD'] == "GET"){

			$resultat_session = new Container('resultatsession');
			
			$paramsUrl = $this->getRequest()->getQuery()->toArray();

			if(count($paramsUrl) == 0 ) {

				if( isset( $resultat_session->data ) ) {
					echo json_encode(  $resultat_session->data );
				}
			} else {
    			$sejoursFiltres = $this->NouvelleRecherche();
    			
				echo json_encode( $sejoursFiltres );
			}

		}
	
		return $this->response;
	}

	private function NouvelleRecherche() {
		$filtreRequete = $this->getRequest()->getQuery()->toArray();

		$filtreRequete['tags'] =  isset($filtreRequete['tags']) ? explode( ",", $filtreRequete['tags'] ) : array();
		$filtreRequete['pays'] = isset($filtreRequete['pays']) ? explode( ",", $filtreRequete['pays'] ) : array();
		$filtreRequete['regions'] = isset($filtreRequete['regions']) ? explode( ",", $filtreRequete['regions'] ) : array();
		$filtreRequete['activites'] = isset($filtreRequete['activites']) ? explode( ",", $filtreRequete['activites'] ) : array();
		$filtreRequete['thematiques'] = isset($filtreRequete['thematiques']) ? explode( ",", $filtreRequete['thematiques'] ) : array();

		return $this->getRechercheSejourTable()->filtrerLesSejours( $filtreRequete );
	}

	/*************************************************************************************************************/

	public function getRechercheSejourTable()
	{
		if( !$this->RechercheSejourTable ){
			$sm = $this->getServiceLocator();
			$this->RechercheSejourTable = $sm->get("Application\Model\RechercheSejourTable");
		}
		return $this->RechercheSejourTable;
	}
}
